//
// Created by yonghu0 on 25-11-2.
//

#include "RedisDataBase.h"
#include "Config.h"


ReDB::ReDB()
{
    m_redis_token = new Redis(Config::GetInstance().GetValue("redis_token_connect"));
    m_redis_cache = new Redis(Config::GetInstance().GetValue("redis_cache_connect"));
}

ReDB::~ReDB()
{
}

ReDB *ReDB::GetInstance()
{
    static ReDB redis;
    return &redis;
}

bool ReDB::SetToken(std::string token, std::string userid)
{
    try
    {
        m_redis_token->setex(token, 604800, userid);
        return true;
    } catch (std::exception &e)
    {
        return false;
    }
}

std::string ReDB::GetUserIdByToken(std::string token)
{
    try
    {
        auto res = m_redis_token->get(token);
        if (res)
            return *res;
        else
            return "0";
    } catch (std::exception &e)
    {
        return "0";
    }
}

bool ReDB::AddProblemCache(std::string problemid, std::string probleminfo)
{
    std::string id = "Cache:Problem:" + problemid;
    try
    {
        m_redis_cache->setex(id, 86400, probleminfo);
        return true;
    } catch (const std::exception &e)
    {
        return false;
    }
}

std::string ReDB::GetProblemCache(std::string problemid)
{
    std::string id = "Cache:Problem:" + problemid;
    try
    {
        auto res = m_redis_cache->get(id);
        if (res)
            return *res;
        else
            return "";
    } catch (const std::exception &e)
    {
        return "";
    }
}

bool ReDB::DeleteProblemCache(std::string problemid)
{
    std::string id = "Cache:Problem:" + problemid;
    try
    {
        return m_redis_cache->del(id);
    } catch (const std::exception &e)
    {
        return false;
    }
}

bool ReDB::AddStatusRecordCache(std::string statusrecordid, std::string statusrecordinfo)
{
    std::string id = "Cache:StatusRecord:" + statusrecordid;
    try
    {
        m_redis_cache->setex(id, 86400, statusrecordinfo);
        return true;
    } catch (const std::exception &e)
    {
        return false;
    }
}

std::string ReDB::GetStatusRecordCache(std::string statusrecordid)
{
    std::string id = "Cache:StatusRecord:" + statusrecordid;
    try
    {
        auto res = m_redis_cache->get(id);
        if (res)
            return *res;
        else
            return "";
    } catch (const std::exception &e)
    {
        return "";
    }
}
